<template>
<div class="search">
  <input type="text" placeholder="输入城市名或拼音" class="search-input" v-model="keyword">
  <div class="search-content" ref="wrapper" v-show="keyword">
    <ul>
      <li
        v-for="item of list"
        class="search-item border-bottom"
        :key="item.id"
        @click="handleChangeCity(item.name)"
      >{{item.name}}</li>
      <li v-show="noData" class="search-item border-bottom">
        找不到您搜索的城市
      </li>
    </ul>
  </div>
</div>
</template>

<script>
    import BScroll from 'better-scroll'
    export default {
        props: {
          cities: Object
        },
        name: "CitySearch",
        data(){
          return {
            keyword:'',
            list:[],
            timer:null
          }
        },
        methods:{
          handleChangeCity(city){
            // 调用store里的actions,当有延迟操作或者ajax数据请求的时候需要调用actions的方法
            //   this.$store.dispatch("changeCity",city)

            // 客户端里的数据（几大数据类型）操作，直接调用mutations
            // 这里的数据是直接在dom页面上取的，并不是服务器获取来的数据，这数据是现成的，不需要异步操作
            this.$store.commit("changeCityMuta",city)
            this.$router.push("/")
          }
        },
        mounted(){
          this.$nextTick(()=>{
              this.scroll = new BScroll(this.$refs.wrapper)
          })
        },
        computed:{
          noData(){
              return !this.list.length && this.keyword
          }
        },
        watch:{
            // 相当于input方法
          keyword(){
              this.list=[]
              if(this.timer){
                clearTimeout(this.timer)
              }
              // 当没有输入或删掉所有信息时，不显示任何信息
              if(!this.keyword){
                this.list=[]
                return
              }

              this.timer = setTimeout(()=>{
                  for (let key in this.cities){
                   this.cities[key].forEach((value) => {
                       if(value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1){
                          if(value){
                            this.list.push(value)
                          }
                       }
                    })
                  }
              },100)
          }
        }
    }
</script>

<style lang="stylus" scoped>
  @import "~assets/styles/varibles"

  .search
    height 0.72rem
    padding 0 0.1rem
    background $bgColor
    box-sizing border-box
  .search .search-input
    width: 100%
    height 0.62rem
    line-height 0.62rem
    text-align center
    padding 0 0.1rem
    box-sizing: border-box;
    border-radius 0.05rem
  .search-content
   z-index 1
   position absolute
   top 1.54rem
   left 0
   right 0
   bottom 0
   background #eee
   overflow hidden
  .search-item
   line-height 0.62rem
   padding-left: 0.2rem;
   background: #fff;
   color:#666
</style>
